import "./text-overflow.less";
import { createPopper } from "@popperjs/core";

export function directive(Vue) {
  let handleMouseEnter;
  let handleMouseLeave;
  let clearTooltip;

  Vue.directive("overflow", {
    inserted: function (el, binding) {
      const config = {
        placement: binding.value?.placement || "top",
        innerText: el.innerText,
      };

      el.style.display = "inline-block";
      el.style.overflow = "hidden";
      el.style["text-overflow"] = "ellipsis";
      const div = document.createElement("div");
      div.classList.add("ga-popover");
      div.setAttribute("placement", config.placement);
      div.innerHTML = `
    <span>${config.innerText}</span>
    <span class="arrow"></span>
  `;

      handleMouseEnter = () => {
        if (isTextOverflow(el)) {
          document.body.appendChild(div);
          createPopper(el, div, {
            placement: config.placement,
          });
        }
      };

      handleMouseLeave = () => {
        if (isTextOverflow(el)) {
          document.body.removeChild(div);
        }
      };

      clearTooltip = () => {
        if (document.body.contains(div)) {
          document.body.removeChild(div);
        }
      };
      el.addEventListener("mouseenter", handleMouseEnter);
      el.addEventListener("mouseleave", handleMouseLeave);
    },
    unbind: function (el) {
      el.removeEventListener("mouseenter", handleMouseEnter);
      el.removeEventListener("mouseleave", handleMouseLeave);
      // 顺便也保证移除寄生的tooltip元素
      clearTooltip();
    },
  });
}

function isTextOverflow(el) {
  // 判断是否text-overflow
  const range = document.createRange();
  range.setStart(el, 0);
  range.setEnd(el, el.childNodes.length);
  const rangeWidth = range.getBoundingClientRect().width;
  const padding =
    (parseInt(el.style.paddingLeft, 10) || 0) +
    (parseInt(el.style.paddingRight, 10) || 0);
  if (
    rangeWidth + padding > el.offsetWidth ||
    el.scrollWidth > el.offsetWidth
  ) {
    return true;
  }
  return false;
}
